<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 17-4-9
 * Time: 15:22
 */

namespace frontend\models;


use yii\base\Model;

class LoginForm extends Model
{
    public $username;
    public $password;
    public $verifyCode;
    public $messageCode;
    public $tel;
    public $rememberMe =true;
    public $openid=0;


    public function rules()
    {
        return [
            [['username','password','verifyCode',/*'messageCode',*/'tel'],'required'],
            [['tel'], 'string', 'length' => 11],
            [['password'],'string','max'=>32],
            [['verifyCode'],'captcha'],
            [['rememberMe'],'boolean'],
            [['messageCode'],'validatesmsCode'],
        ];
    }

    public function validateTel($attr,$params){
        if(strlen($attr) != 11){
            $this->addError($attr,'手机号码不符合要求');
        }
    }

    public function validatesmsCode()
    {
        $code = \Yii::$app->session->get('tel_'.$this->tel);
        if($this->messageCode != $code){
            $this->addError('messageCode','短信验证码输入错误');
        }
    }

    public function attributeLabels()
    {
        return [
            'username'=>'用户名：',
            'password'=>'密码：',
            'verifyCode'=>'验证码：',
            'messageCode'=>'手机验证：',
            'tel'=>'手机号码：',
            'rememberMe'=>'',

        ];
    }

    public function login(){
        //通过用户名字找到用户的信息
        $memberInfo = Member::findOne(['username'=>$this->username]);
        //验证密码是否正确
        $rs = \Yii::$app->security->validatePassword($this->password,$memberInfo->password_hash);
        //如果用户的密码正确,则登录

        if($rs){
            $r = \Yii::$app->user->login($memberInfo,$this->rememberMe?3600*24:0);
            //登录成功后更新用户的信息
            $memberInfo->openid = $this->openid;
            $memberInfo->last_login_ip = ip2long(\Yii::$app->request->getUserIP());
            $memberInfo->last_login_time = time();
            $memberInfo->save(false);//保存信息
            //用户登录成功
        }
        return $rs;



    }


}